import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import json5

from utils.static import STEAM_ACCOUNT_INFO_FILE_PATH

class SteamAccountConfigWindow:
    def __init__(self, parent):
        """
        创建Steam账号配置窗口
        
        Args:
            parent: 父窗口，通常是主窗口
        """
        self.parent = parent
        self.steam_window = None
        self.is_open = False
        
    def open(self):
        """打开Steam账号配置窗口"""
        # 如果窗口已经打开，则不再创建新窗口
        if self.is_open:
            self.steam_window.focus_force()
            return
            
        try:
            # 创建新窗口
            self.steam_window = tk.Toplevel(self.parent)
            self.steam_window.title("Steam账号配置")
            self.steam_window.geometry("600x400")
            # 设置为模态窗口
            self.steam_window.transient(self.parent)
            self.steam_window.grab_set()
            self.steam_window.focus_set()
            # 设置窗口关闭事件
            self.steam_window.protocol("WM_DELETE_WINDOW", self.on_close)
            # 标记窗口已打开
            self.is_open = True

            # 居中显示窗口
            self.center_window(self.steam_window, 600, 400)
            
            # 创建主框架
            main_frame = ttk.Frame(self.steam_window)
            main_frame.pack(fill='both', expand=True, padx=10, pady=5)

            # 创建表单框架
            form_frame = ttk.Frame(main_frame)
            form_frame.pack(fill='x', padx=5, pady=10)

            # 变量初始化
            self.username_var = tk.StringVar()
            self.password_var = tk.StringVar()
            self.shared_secret_var = tk.StringVar()
            self.identity_secret_var = tk.StringVar()

            # 创建文件选择框架
            file_frame = ttk.Frame(main_frame)
            file_frame.pack(fill='x', padx=5, pady=5)
            
            # 添加文件选择按钮和帮助超链接
            file_btn_frame = ttk.Frame(file_frame)
            file_btn_frame.pack(fill='x', padx=0, pady=0)
            select_btn = ttk.Button(
                file_btn_frame,
                text="选择 Steam Guard 文件",
                command=self.select_mafile
            )
            select_btn.pack(side='left', pady=5)

            # 添加"不会提取？"超链接样式标签
            help_link = tk.Label(file_btn_frame, text="不知道如何提取Steam Guard文件？", fg="#1a73e8", cursor="hand2", font=("Microsoft YaHei", 10, "underline"))
            help_link.pack(side='left', padx=10, pady=5)

            # 鼠标悬停和点击效果
            def on_link_enter(e):
                help_link.config(fg="#0b59d9")
            def on_link_leave(e):
                help_link.config(fg="#1a73e8")
            help_link.bind("<Enter>", on_link_enter)
            help_link.bind("<Leave>", on_link_leave)
            help_link.bind("<Button-1>", lambda e: self.show_help_dialog())

            # 创建输入框
            ttk.Label(form_frame, text="Steam账号:", width=20).grid(row=0, column=0, padx=5, pady=5, sticky='w')
            ttk.Entry(form_frame, textvariable=self.username_var, width=40).grid(row=0, column=1, padx=5, pady=5, sticky='ew')
            
            ttk.Label(form_frame, text="Steam密码:", width=20).grid(row=1, column=0, padx=5, pady=5, sticky='w')
            ttk.Entry(form_frame, textvariable=self.password_var, show='*', width=40).grid(row=1, column=1, padx=5, pady=5, sticky='ew')
            
            ttk.Label(form_frame, text="身份令牌(shared_secret):", width=20).grid(row=2, column=0, padx=5, pady=5, sticky='w')
            ttk.Entry(form_frame, textvariable=self.shared_secret_var, width=40).grid(row=2, column=1, padx=5, pady=5, sticky='ew')
            
            ttk.Label(form_frame, text="身份密钥(identity_secret):", width=20).grid(row=3, column=0, padx=5, pady=5, sticky='w')
            ttk.Entry(form_frame, textvariable=self.identity_secret_var, width=40).grid(row=3, column=1, padx=5, pady=5, sticky='ew')

            # 设置网格列的权重
            form_frame.columnconfigure(1, weight=1)

            # 添加保存和关闭按钮
            button_frame = ttk.Frame(main_frame)
            button_frame.pack(pady=20)
            ttk.Button(button_frame, text="保存配置", command=self.save_account).pack(side='left', padx=5)
            ttk.Button(button_frame, text="关闭", command=self.on_close).pack(side='left', padx=5)

            # 尝试加载现有配置
            try:
                with open(STEAM_ACCOUNT_INFO_FILE_PATH, 'r', encoding='utf-8') as f:
                    existing_config = json5.load(f)
                    self.username_var.set(existing_config.get('steam_username', ''))
                    self.password_var.set(existing_config.get('steam_password', ''))
                    self.shared_secret_var.set(existing_config.get('shared_secret', ''))
                    self.identity_secret_var.set(existing_config.get('identity_secret', ''))
            except:
                pass

        except Exception as e:
            messagebox.showerror("错误", f"无法打开Steam账号配置：{str(e)}")
    
    def select_mafile(self):
        """选择并读取 .maFile 文件"""
        file_path = filedialog.askopenfilename(
            title="选择 .maFile 文件",
            filetypes=[("Steam Guard 文件", "*.maFile"), ("所有文件", "*.*")]
        )
        if file_path:
            try:
                with open(file_path, 'r', encoding='utf-8') as f:
                    ma_data = json5.load(f)
                
                # 自动填充表单
                if 'account_name' in ma_data:
                    self.username_var.set(ma_data['account_name'])
                if 'shared_secret' in ma_data:
                    self.shared_secret_var.set(ma_data['shared_secret'])
                if 'identity_secret' in ma_data:
                    self.identity_secret_var.set(ma_data['identity_secret'])
                
                messagebox.showinfo("成功", "已成功读取令牌文件信息！")
            except Exception as e:
                messagebox.showerror("错误", f"读取文件失败：{str(e)}")
    
    def save_account(self):
        """保存账号配置到文件"""
        try:
            account_data = {
                "steam_username": self.username_var.get(),
                "steam_password": self.password_var.get(),
                "shared_secret": self.shared_secret_var.get(),
                "identity_secret": self.identity_secret_var.get()
            }
            
            # 验证必填字段
            if not all(account_data.values()):
                messagebox.showwarning("警告", "请填写所有必填字段！")
                return
            
            with open(STEAM_ACCOUNT_INFO_FILE_PATH, 'w', encoding='utf-8') as f:
                json5.dump(account_data, f, indent=2)
            messagebox.showinfo("成功", "Steam账号配置已保存！")
            self.steam_window.grab_release()
            self.steam_window.destroy()
        except Exception as e:
            messagebox.showerror("错误", f"保存Steam账号配置失败：{str(e)}")

    def on_close(self):
        """关闭窗口"""
        if self.steam_window:
            self.steam_window.grab_release()
            self.steam_window.destroy()
            self.steam_window = None
            self.is_open = False
    
    def show_help_dialog(self):
        """显示帮助对话框"""
        help_win = tk.Toplevel(self.steam_window)
        help_win.title("获取帮助")
        help_win.geometry("320x200")
        help_win.transient(self.steam_window)
        help_win.grab_set()
        help_win.focus_set()
        
        # 居中
        def center_help(win, width, height):
            parent_x = self.steam_window.winfo_rootx()
            parent_y = self.steam_window.winfo_rooty()
            parent_width = self.steam_window.winfo_width()
            parent_height = self.steam_window.winfo_height()
            x = parent_x + (parent_width - width) // 2
            y = parent_y + (parent_height - height) // 2
            win.geometry(f"{width}x{height}+{x}+{y}")
            
        center_help(help_win, 320, 200)
        
        # 联系方式内容
        tk.Label(help_win, text="如需人工协助提取 Steam Guard 文件：", font=("Microsoft YaHei", 10), anchor='center', justify='center').pack(pady=(18,8), fill='x')
        tk.Label(help_win, text="QQ群：1025778678", font=("Microsoft YaHei", 11, "bold"), fg="#0078d7").pack(pady=2)
        tk.Label(help_win, text="微信：bja1487580811", font=("Microsoft YaHei", 11, "bold"), fg="#43b244").pack(pady=2)
        tk.Label(help_win, text="添加微信请备注'Steamauto'", font=("Microsoft YaHei", 9), fg="#888888").pack(pady=(8,0))
        
        # 关闭帮助窗口时恢复父窗口的模态状态
        def close_help():
            help_win.destroy()
            # 确保主配置窗口重新获得焦点和模态状态
            self.steam_window.focus_set()
            self.steam_window.grab_set()
            
        tk.Button(help_win, text="关闭", command=close_help).pack(pady=15)
        
        # 设置关闭事件
        help_win.protocol("WM_DELETE_WINDOW", close_help)
    
    def center_window(self, window, width, height):
        """居中显示窗口"""
        parent_x = self.parent.winfo_rootx()
        parent_y = self.parent.winfo_rooty()
        parent_width = self.parent.winfo_width()
        parent_height = self.parent.winfo_height()
        
        # 若主窗口还未显示，fallback 到屏幕居中
        if parent_width == 1 or parent_height == 1:
            screen_width = window.winfo_screenwidth()
            screen_height = window.winfo_screenheight()
            x = (screen_width - width) // 2
            y = (screen_height - height) // 2
        else:
            x = parent_x + (parent_width - width) // 2
            y = parent_y + (parent_height - height) // 2
            
        window.geometry(f"{width}x{height}+{x}+{y}")
